package com.example.statistics.ui.print

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothClass
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import com.example.statistics.R
import com.example.statistics.bean.BluetoothDeviceBean
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.loadingDialog
import com.example.statistics.ex.slimAdapter
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.permissions.PermissionsCheck
import com.jhj.prompt.fragment.LoadingFragment
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.itemdecoration.LineItemDecoration
import kotlinx.android.synthetic.main.activity_bluetooth.*
import org.jetbrains.anko.toast

class BlueToothActivity : BaseActivity() {

    private val TAG = "bluetooth"
    private var dialog: LoadingFragment.Builder? = null
    var deviceList = mutableListOf<BluetoothDeviceBean>()
    var adapter: SlimAdapter? = null
    var mBluetoothAdapter: BluetoothAdapter? = null
    override val title: String
        get() = "选择打印机"


    private val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            var device: BluetoothDevice? = null
            when (action) {
                BluetoothDevice.ACTION_FOUND -> {
                    device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    //如果设置是打印机设备
                    if (device.bluetoothClass.majorDeviceClass == BluetoothClass.Device.Major.IMAGING) {
                        val bean = BluetoothDeviceBean()
                        bean.name = device.name
                        bean.address = device.address
                        deviceList.add(bean)
                        adapter?.addData(bean)
                        if (dialog?.isShow() == true)
                            dialog?.dismiss()
                    }
                }
                BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
                    Log.w(TAG, "正在扫描，请耐心等待")
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    Log.w(TAG, "搜索完成")
                    if (dialog?.isShow() == true)
                        dialog?.dismiss()
                }
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bluetooth)
        dialog = loadingDialog("正在扫描中...")
        recycler_view.addItemDecoration(LineItemDecoration())
        adapter = slimAdapter<BluetoothDeviceBean>(R.layout.list_item_bluetooth) { bean ->
            text(R.id.tv_name, bean.name)
            text(R.id.tv_address, bean.address)
            clicked {
                activityFinish("data" to bean.address)
                finish()
            }
        }.attachTo(recycler_view)

        doDiscovery()
    }

    private fun registerBroadcast() {
        val filter = IntentFilter()
        filter.addAction(BluetoothDevice.ACTION_FOUND) // 用BroadcastReceiver来取得搜索结果
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
        registerReceiver(mReceiver, filter)
    }


    private fun doDiscovery() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (mBluetoothAdapter == null) {
            toast("该设备不支持蓝牙功能")
            return
        } else if (mBluetoothAdapter?.isEnabled == false) {
            mBluetoothAdapter?.enable()
        }
        registerBroadcast()
        PermissionsCheck.with(this)
                .requestPermissions(Manifest.permission.BLUETOOTH,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .onPermissionsResult { strings, _ ->
                    if (strings.isEmpty()) {
                        if (null == mBluetoothAdapter) {
                            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
                        }
                        if (mBluetoothAdapter?.isEnabled == false) {
                            mBluetoothAdapter?.enable()
                        }
                        if (mBluetoothAdapter?.isDiscovering == true) {
                            mBluetoothAdapter?.cancelDiscovery()
                        }
                        mBluetoothAdapter?.startDiscovery()
                    } else {
                        toast("蓝牙权限未打开")
                    }
                }
    }

    private fun disReceiver() {
        unregisterReceiver(mReceiver)
        if (mBluetoothAdapter?.isDiscovering == true)
            mBluetoothAdapter?.cancelDiscovery()
    }


    /**
     * 获取所有已配对的设备
     */
    fun getPairedDevices(): List<BluetoothDeviceBean> {
        val deviceList: MutableList<BluetoothDeviceBean> = ArrayList()
        val pairedDevices = BluetoothAdapter.getDefaultAdapter().bondedDevices
        if (pairedDevices.size > 0) {
            for (device in pairedDevices) {
                val klass = device.bluetoothClass
                // 关于蓝牙设备分类参考 http://stackoverflow.com/q/23273355/4242112
                // 具体分类：https://blog.csdn.net/strivebus/article/details/65628628
                if (klass.majorDeviceClass == BluetoothClass.Device.Major.IMAGING) {
                    val bean = BluetoothDeviceBean()
                    bean.name = device.name
                    bean.address = device.address
                    deviceList.add(bean)
                }
            }
        }
        return deviceList
    }

    override fun onDestroy() {
        super.onDestroy()
        disReceiver()
    }


}